package org.i1510.joeone.controller;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.jxls.transformer.XLSTransformer;

import org.i1510.common.bean.PageBean;
import org.i1510.common.utils.StringUtils;
import org.i1510.common.utils.UserUtils;
import org.i1510.common.utils.web.ResultMapper;
import org.i1510.common.utils.web.WebUtils;
import org.i1510.joeone.dao.IDhVoteDao;
import org.i1510.joeone.po.DhVote;
import org.i1510.joeone.po.JoeSubj2Class;
import org.i1510.joeone.po.JoeoneCode;
import org.i1510.joeone.po.JoeoneConf;
import org.i1510.joeone.service.IDhVoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/admin/dhVote")
public class DhVoteController {
    private static final Logger logger = LoggerFactory.getLogger(DhVoteController.class);
    @Autowired
    private IDhVoteService iDhVoteService;
    @Autowired
    private IDhVoteDao iDhVoteDao;
    
    private ResultMapper mapper;

    
    @RequestMapping(value = "/downloadStat", method = RequestMethod.GET)
    @ResponseBody
    public String downloadStat(HttpServletRequest request,HttpServletResponse response,@Valid @ModelAttribute("dhVote") DhVote dhVote,@Valid @ModelAttribute("pageBean") PageBean pageBean,BindingResult errors) 
    		throws Exception {
        ResultMapper mapperRtn = ResultMapper.generateFailure();
        if(errors.hasErrors()){            
            mapperRtn = WebUtils.getMapper4Errors(errors);
        }else{
	        	Map conditions = new HashMap();
	            conditions.put("jconf", request.getParameter("jconf"));
	            List stat = iDhVoteService.getStat(dhVote, conditions);
	            
	            Map map = new HashMap();
	            map.put("listData",stat);
	            mapperRtn = ResultMapper.generateSuccess();
	            mapperRtn.appendResult("data", map);
            
//              String templateFileName = (new StringBuilder("")).append("/Users/rambo/tmpl1.xls").toString();
//        		String destFileName = (new StringBuilder("")).append("/Users/rambo/tmp.xls").toString();
        		
//        		String templateFileName = (new StringBuilder("")).append("D:/ipad4joeone/tmpl1.xls").toString();
//        		String destFileName = (new StringBuilder("")).append("D:/ipad4joeone/tmp.xls").toString();

                
        		String templateFileName = (new StringBuilder("")).append(request.getSession().getServletContext().getRealPath("/")+"joeone/ipad/tmpl21.xls").toString();
        		String destFileName = (new StringBuilder("")).append(request.getSession().getServletContext().getRealPath("/")+"joeone/ipad/tmp2.xls").toString();
        		
        		Map beans = new HashMap();
        		for (int i = 0; i < stat.size(); i++) {
        			Map mapStat = (Map)stat.get(i);
					beans.put("jclass_"+mapStat.get("jclass"), mapStat);
				}

        		XLSTransformer transformer = new XLSTransformer();
        		try {
        			transformer.transformXLS(templateFileName, beans, destFileName);
        		} catch (Exception e) {
        			e.printStackTrace();
        		}
        		FileInputStream is = new FileInputStream(destFileName);
        		response.setContentType("application/x-msdownload");
        		response.setHeader("Content-Disposition", "attachment; filename="
        				+ "out.xls");
        		OutputStream outputStream = response.getOutputStream();
        		byte[] buffer = new byte[1024];
        		int i = -1;
        		while ((i = is.read(buffer)) != -1) {
        			outputStream.write(buffer, 0, i);
        		}
        		outputStream.flush();
        		outputStream.close();
        		is.close();
        		return null;
        		
        
            
            
            
        }        
        return null;
    }
    
    
    @RequestMapping(value = "/getUserStat", method = RequestMethod.POST)
    @ResponseBody
    public String getUserStat(HttpServletRequest request,@Valid @ModelAttribute("dhVote") DhVote dhVote,BindingResult errors) {
        ResultMapper mapperRtn = ResultMapper.generateFailure();
        if(errors.hasErrors()){            
            mapperRtn = WebUtils.getMapper4Errors(errors);
        }else{
            Map conditions = new HashMap();
            conditions.put("area", request.getParameter("area"));
            conditions.put("company", request.getParameter("company"));
            conditions.put("jconf", request.getParameter("jconf"));
            System.out.println(request.getParameter("area"));
            System.out.println(request.getParameter("company"));
            if(request.getParameter("isnote").equals("1")){
                conditions.put("isnote1", request.getParameter("isnote"));
            }else{
                conditions.put("isnote0", request.getParameter("isnote"));
            }
            List stat = iDhVoteService.getUserStat(dhVote, conditions);
            
            Map map = new HashMap();
            map.put("listData",stat);
            mapperRtn = ResultMapper.generateSuccess();
            mapperRtn.appendResult("data", map);
           
            
        }        
        return mapperRtn.toJson();
    }
    
    @RequestMapping(value = "/getStat", method = RequestMethod.GET)
    @ResponseBody
    public String getStat(HttpServletRequest request,@Valid @ModelAttribute("dhVote") DhVote dhVote,BindingResult errors) {
        ResultMapper mapperRtn = ResultMapper.generateFailure();
        if(errors.hasErrors()){            
            mapperRtn = WebUtils.getMapper4Errors(errors);
        }else{
            Map conditions = new HashMap();
            conditions.put("jconf", request.getParameter("jconf"));
            List stat = iDhVoteService.getStat(dhVote, conditions);
            
            Map map = new HashMap();
            map.put("listData",stat);
            mapperRtn = ResultMapper.generateSuccess();
            mapperRtn.appendResult("data", map);
           
            
        }        
        return mapperRtn.toJson();
    }

    /**
    *@Author Rambo
    *@Desc：提交投票
    *@param request
    *@param dhVote
    *@param errors
    *@return TODO
    *@Version  DhVoteController.java,v 1.1 2015年7月30日 下午5:47:59 
    */
    @RequestMapping(value = "/saveVote", method = RequestMethod.POST)
    @ResponseBody
    public String saveVote(HttpServletRequest request,@Valid @ModelAttribute("dhVote") DhVote dhVote,BindingResult errors) {
        
        if(errors.hasErrors()){            
            mapper = WebUtils.getMapper4Errors(errors);
        }else{
        	//本次需要执行收集的品类ID jclass
        	String[] strs = {"18","17","20","22","30","7","1","10","31","32","33","34","35","3","36","37"
        			,"38","39","40","41","42","2","12","16","9","25","26","27","28","29"};
        	
        	for(int i=0 ;i < strs.length ;i++){
        		DhVote vote = new DhVote();
        		vote.setDocId(request.getParameter("docId_"+strs[i]));
        		vote.setJconf(request.getParameter("jconf"));
        		vote.setDocStatus("10");
        		vote.setPj(request.getParameter("pj_"+strs[i]));
        		vote.setIsbc(request.getParameter("isbc_"+strs[i]) );
        		vote.setJclass(request.getParameter("jclass_"+strs[i]) );
        		iDhVoteService.save(vote,request);
        	}
        	mapper = ResultMapper.generateSuccess();
        	mapper.appendResult("messages", "提交成功!");
        }
        
        return mapper.toJson();
    }
    /**
    *@Author Rambo
    *@Desc：获取投票结果
    *@param request
    *@param dhVote
    *@param pageBean
    *@param errors
    *@return TODO
    *@Version  DhVoteController.java,v 1.1 2015年7月30日 下午5:47:46 
    */
    @RequestMapping(value = "/getVote", method = RequestMethod.GET)
    @ResponseBody
    public String list(HttpServletRequest request,@Valid @ModelAttribute("dhVote") DhVote dhVote,@Valid @ModelAttribute("pageBean") PageBean pageBean,BindingResult errors) {
        ResultMapper mapperRtn = ResultMapper.generateFailure();
        if(errors.hasErrors()){            
            mapperRtn = WebUtils.getMapper4Errors(errors);
        }else{
        	 Map conditions = new HashMap();
        	 
        	 if(null != dhVote){
        		 dhVote.setDocCreator(UserUtils.getSessionUserBean(request).getSysUser().getDocId());
        		 if(dhVote.getJconf().equals("")){
        			 mapperRtn = ResultMapper.generateFailure();
                     mapperRtn.appendResult("message", "数据错误!");
                     return mapperRtn.toJson();
        		 }
        	 }
             List  dhVotes = iDhVoteService.getPage(dhVote, pageBean,conditions);
             int totalCount =  iDhVoteService.getPageCount(dhVote,conditions);
             Map map = new HashMap();
             map.put("pageNo", pageBean.getPageNo());
             map.put("pageSize", pageBean.getPageSize());
             map.put("totalCount", totalCount);
             map.put("listData",dhVotes);
             
             mapperRtn = ResultMapper.generateSuccess();
             mapperRtn.appendResult("data", map);
            
        }        
        return mapperRtn.toJson();
    }
    /**
    *@Author Rambo
    *@Desc：保存对象
    *@param dhVote
    *@param errors
    *@return TODO
    *@Version  DhVoteController.java,v 1.1 2013-11-15 下午4:20:56 
    */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public String save(HttpServletRequest request,@Valid @ModelAttribute("dhVote") DhVote dhVote,BindingResult errors) {
        
        if(errors.hasErrors()){            
            mapper = WebUtils.getMapper4Errors(errors);
        }else{
            dhVote.setDocStatus("10");
            mapper = iDhVoteService.save(dhVote,request);
        }
        
        return mapper.toJson();
    }
    /**
    *@Author Rambo
    *@Desc：删除对象
    *@param docId
    *@param errors
    *@return TODO
    *@Version  DhVoteController.java,v 1.1 2014-9-2 下午3:38:17 
    */
    @RequestMapping(value = "/deleteX", method = RequestMethod.POST)
    @ResponseBody
    public String deleteX(@Valid @ModelAttribute("docId") String docId,BindingResult errors) {
        
        if(errors.hasErrors()){            
            mapper = WebUtils.getMapper4Errors(errors);
        }else{
            mapper = iDhVoteService.delete(docId);
        }
        
        return mapper.toJson();
    }
    /**
    *@Author Rambo
    *@Desc：查看对象
    *@param docId
    *@param errors
    *@return TODO
    *@Version  DhVoteController.java,v 1.1 2014-9-2 下午3:39:35 
    */
    @RequestMapping(value = "/view", method = RequestMethod.GET)
    @ResponseBody
    public String view(@Valid @ModelAttribute("docId") String docId,BindingResult errors) {
        ResultMapper mapperRtn = ResultMapper.generateFailure();
        if(errors.hasErrors()){            
            mapperRtn = WebUtils.getMapper4Errors(errors);
        }else{
            DhVote dhVote = iDhVoteService.findById(docId);
            mapperRtn = ResultMapper.generateSuccess();
            mapperRtn.appendResult("data", dhVote);
        }        
        return mapperRtn.toJson();
    }
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public String list(@ModelAttribute("fromDate") String fromDate,@ModelAttribute("toDate") String toDate,@Valid @ModelAttribute("dhVote") DhVote dhVote,@Valid @ModelAttribute("pageBean") PageBean pageBean,BindingResult errors) {
        ResultMapper mapperRtn = ResultMapper.generateFailure();
        if(errors.hasErrors()){            
            mapperRtn = WebUtils.getMapper4Errors(errors);
        }else{
            Map conditions = new HashMap();
            conditions.put("fromDate", fromDate);
            conditions.put("toDate", toDate);
            List  dhVotes = iDhVoteService.getPage(dhVote, pageBean,conditions);
            int totalCount =  iDhVoteService.getPageCount(dhVote,conditions);
            Map map = new HashMap();
            map.put("pageNo", pageBean.getPageNo());
            map.put("pageSize", pageBean.getPageSize());
            map.put("totalCount", totalCount);
            map.put("listData",dhVotes);
            
            mapperRtn = ResultMapper.generateSuccess();
            mapperRtn.appendResult("data", map);
        }        
        return mapperRtn.toJson();
    }
    /**
    *@Author Rambo
    *@Desc：状态修改
    *@param request
    *@param docId
    *@param docStatus
    *@param errors
    *@return TODO
    *@Version  CateController.java,v 1.1 2014-9-11 上午10:06:04 
    */
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    @ResponseBody
    public String updateStatus(HttpServletRequest request,@Valid @ModelAttribute("docId") String docId,@Valid @ModelAttribute("docStatus") String docStatus,BindingResult errors) {
        
        if(errors.hasErrors()){            
            mapper = WebUtils.getMapper4Errors(errors);
        }else{
            if(!StringUtils.isStringEmpty(docId)){
                DhVote dhVote = new DhVote();
                
                dhVote.setDocId(docId);
                dhVote.setDocStatus(docStatus);
                mapper = iDhVoteService.save(dhVote,request);
            }else{
                mapper = ResultMapper.generateFailure();
                mapper.appendResult("messages", "无法找到该ID!");
            }
            
        }
        
        return mapper.toJson();
    }
}